/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package myapp;

/**
 *
 * @author Saurabh
 */
import java.util.Map;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts2.dispatcher.*;
import org.apache.struts2.interceptor.*;
import org.apache.struts2.util.*;

public class Default implements SessionAware, ServletRequestAware, ServletResponseAware, ServletContextAware {

    private String userName, password;
    private ServletResponse sRes;
    private ServletRequest sReq;
    private ServletContext sContext;
    private Map sessionMap;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setServletResponse(HttpServletResponse sRes) {
        this.sRes = sRes;
    }

    public void setServletRequest(HttpServletRequest sReq) {
        this.sReq = sReq;
    }

    public void setServletContext(ServletContext sContext) {
        this.sContext = sContext;
    }

    public void setSession(Map sessionMap) {
        this.sessionMap = sessionMap;
    }

    public String login() {
        String wasLogin = (String) sessionMap.get("login");
        try {
            if (wasLogin != null && wasLogin.equals("true")) {
                return "success";
            } else if (userName.equals("admin") && password.equals("admin")) {
                if (sessionMap instanceof SessionMap) {
                    ((SessionMap) sessionMap).invalidate();
                }
                setSession(sessionMap);
                int onlineUserCount = 0;
                synchronized (sContext) {
                    try {
                        onlineUserCount = (Integer) sContext.getAttribute("onlineUserCount");
                    } catch (Exception e) {
                        System.err.println(e);
                    }
                    sContext.setAttribute("onlineUserCount", onlineUserCount + 1);
                }
                sessionMap.put("login", "true");
                sessionMap.put("username", userName);
                return "success";
            }
        } catch (Exception e) {
            System.err.println(e);
            return "input";
        }
        return "input";
    }

    public String logout() {
        try {
            if (sessionMap instanceof SessionMap && ((String) sessionMap.get("login")).equals("true")) {
                ((SessionMap) sessionMap).invalidate();
            }
        } catch (Exception e) {
            System.err.println(e);
        }
        return "success";
    }

}
